package com.xiangge.aliyun.aliyuntest.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiangge.aliyun.aliyuntest.entity.ExpressInfo;
import com.xiangge.aliyun.aliyuntest.enums.ShippingEnum;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.RequestEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lsy_server
 */
@Service
public class ExpressService {
    @Autowired
    private RestTemplate restTemplate;
    private static String url = "http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";

    public ExpressInfo getExpressInfo(ShippingEnum ship, String expNo) {
        try {
            String result = getOrderTracesByJson(ship, expNo);
            ObjectMapper objMap = new ObjectMapper();
            ExpressInfo ei = objMap.readValue(result, ExpressInfo.class);
            ei.setShipperName(ship.getCode());
            return ei;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private String getOrderTracesByJson(ShippingEnum ship, String expNo) throws Exception {

        String requestData = "{'OrderCode':'','ShipperCode':'" + ship.getCode() + "','LogisticCode':'" + expNo + "'}";
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("accept", "*/*");
        requestHeaders.add("connection", "Keep-Alive");
        requestHeaders.add("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        requestHeaders.add("Content-Type", "application/json");

        Map<String, String> params = new HashMap<String, String>();
        params.put("RequestData", URLEncoder.encode(requestData, "UTF-8"));
        params.put("EBusinessID", "1605965");
        params.put("RequestType", "1002");
        String dataSign = encrypt(requestData, "637b8049-82d9-4222-b49c-e87dac6564a0", "UTF-8");
        params.put("DataSign", URLEncoder.encode(dataSign, "UTF-8"));
        params.put("DataType", "2");
        HttpEntity<Map> requestEntity = new HttpEntity<>(params, requestHeaders);
        String result = HttpUtil.sendPost(url, params);

        //根据公司业务处理返回的信息......

        return result;
    }


    private String encrypt(String content, String keyValue, String charset) {
        if (keyValue != null) {
            content = content + keyValue;
        }
        byte[] src;
        try {
            src = MD5(content, charset).getBytes(charset);
            return Base64Utils.encodeToString(src);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private String MD5(String str, String charset) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes(charset));
        byte[] result = md.digest();
        StringBuilder sb = new StringBuilder(32);
        for (int i = 0; i < result.length; i++) {
            int val = result[i] & 0xff;
            if (val <= 0xf) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val));
        }
        return sb.toString().toLowerCase();
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @return 远程资源的响应结果
     */
    public static class HttpUtil {

        private static final Log logger = LogFactory.getLog(HttpUtil.class);

        /**
         * 向指定 URL 发送POST方法的请求
         *
         * @param url    发送请求的 URL
         * @param params 请求的参数集合
         * @return 远程资源的响应结果
         */
        @SuppressWarnings("unused")
        public static String sendPost(String url, Map<String, String> params) {
            OutputStreamWriter out = null;
            BufferedReader in = null;
            StringBuilder result = new StringBuilder();
            try {
                URL realUrl = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
                // 发送POST请求必须设置如下两行
                conn.setDoOutput(true);
                conn.setDoInput(true);
                // POST方法
                conn.setRequestMethod("POST");
                // 设置通用的请求属性
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent",
                        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.connect();
                // 获取URLConnection对象对应的输出流
                out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
                // 发送请求参数
                if (params != null) {
                    StringBuilder param = new StringBuilder();
                    for (Map.Entry<String, String> entry : params.entrySet()) {
                        if (param.length() > 0) {
                            param.append("&");
                        }
                        param.append(entry.getKey());
                        param.append("=");
                        param.append(entry.getValue());

                    }

                    out.write(param.toString());
                }
                // flush输出流的缓冲
                out.flush();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            //使用finally块来关闭输出流、输入流
            finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException ex) {
                    logger.error(ex.getMessage(), ex);
                }
            }
            return result.toString();
        }
    }

}
